package lzyc.pointsManagement.business.service.impl;


import lzyc.pointsManagement.business.attachment.dto.AttachmentsDto;
import lzyc.pointsManagement.business.course.convertor.CourseInfoConvertor;
import lzyc.pointsManagement.business.course.domain.CourseInfo;
import lzyc.pointsManagement.business.course.dto.CourseInfoDto;
import lzyc.pointsManagement.business.course.mapper.CourseInfoMapper;
import lzyc.pointsManagement.business.service.AttachmentsService;
import lzyc.pointsManagement.business.service.CourseInfoService;
import lzyc.pointsManagement.common.core.domain.R;
import lzyc.pointsManagement.common.core.page.PageDomain;
import lzyc.pointsManagement.common.response.ResponseMessage;
import lzyc.pointsManagement.common.response.ResponseMessageUtility;
import lzyc.pointsManagement.common.utils.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author liuyuan
* @description 针对表【course_info】的数据库操作Service实现
* @createDate 2024-03-14 21:02:02
*/
@Service
public class CourseInfoServiceImpl implements CourseInfoService {

    private final AttachmentsService attachmentsService;

    private final CourseInfoMapper courseInfoMapper;

    CourseInfoServiceImpl(AttachmentsService attachmentsService, CourseInfoMapper courseInfoMapper) {
        this.attachmentsService = attachmentsService;
        this.courseInfoMapper = courseInfoMapper;
    }

    @Override
    public ResponseMessage courseAdd(CourseInfoDto dto) {
        ResponseMessage result;
        try {
            String name = dto.getName();
//            List<CourseInfo> courseInfoList = courseInfoMapper.queryAllByName(name);
//            if (courseInfoList != null && !courseInfoList.isEmpty()) {
//                int score = dto.getScore();
//                if (score == 0) {
//                    if (courseInfoList.stream().anyMatch(courseInfo -> courseInfo.getScore() == score)) {
//                        return ResponseMessageUtility.createError("学习园地名称已存在。");
//                    }
//                } else {
//                    if (courseInfoList.stream().anyMatch(courseInfo -> courseInfo.getScore() > score)) {
//                        return ResponseMessageUtility.createError("课程名称已存在。");
//                    }
//                }
//            }
            CourseInfo entity = CourseInfoConvertor.convertToEntity(dto);
            attachmentsService.batchUpdateBizIds(Arrays.asList(entity.getAttachment(), entity.getFrontCover()), entity.getId());
            courseInfoMapper.addCourseInfo(entity);
            result = ResponseMessageUtility.createSuccess();
        } catch (RuntimeException e) {
            result = ResponseMessageUtility.createError("新增课程失败。" + e.getMessage());
        }
        return result;
    }

    @Override
    public ResponseMessage courseUpdate(CourseInfoDto dto) {
        ResponseMessage result;
        try {
            if (dto != null && !StringUtils.isEmpty(dto.getId())) {
                CourseInfo entity = CourseInfoConvertor.convertToEntity(dto);
                attachmentsService.batchUpdateBizIds(Arrays.asList(entity.getAttachment(), entity.getFrontCover()), entity.getId());
                courseInfoMapper.updateCourseInfo(entity);
                result = ResponseMessageUtility.createSuccess();
            } else {
                result = ResponseMessageUtility.createError("课程id不能为空。");
            }

        } catch (RuntimeException e) {
            result = ResponseMessageUtility.createError("新增课程失败。" + e.getMessage());
        }
        return result;
    }

    @Override
    public ResponseMessage courseDelete(String id) {
        ResponseMessage result;
        try {
            CourseInfo courseInfo = courseInfoMapper.selectCourseInfoById(id);
            attachmentsService.batchUpdateBizIds(Arrays.asList(courseInfo.getAttachment(), courseInfo.getFrontCover()), null);
            courseInfoMapper.deleteCourseInfoById(id);
            result = ResponseMessageUtility.createSuccess();
        } catch (RuntimeException e) {
            result = ResponseMessageUtility.createError("删除课程失败。" + e.getMessage());
        }
        return result;
    }

    @Override
    public ResponseMessage getCourseListByPage(PageDomain pageDomain) {
        ResponseMessage result = ResponseMessageUtility.createSuccess();
        int offset = (pageDomain.getPageNum() - 1) * pageDomain.getPageSize();
        int size = pageDomain.getPageSize();
        List<CourseInfo> courseInfoList = courseInfoMapper.selectCourseInfoListByPage(offset, size);
        if (courseInfoList != null && !courseInfoList.isEmpty()) {
            List<CourseInfoDto> courseInfoDtoList = new ArrayList<>();
            courseInfoList.forEach(courseInfo -> {
                String frontCover = courseInfo.getFrontCover();
                CourseInfoDto courseInfoDto = CourseInfoConvertor.convertToDto(courseInfo);
                courseInfoDto.setFrontCoverDetail(attachmentsService.getAttachmentsDtoById(frontCover));
                Date currentTime = new Date();
                if (courseInfoDto.getEndTime() != null) {
                    LocalDate localDate1 = currentTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    LocalDate localDate2 = courseInfoDto.getEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    courseInfoDto.setAvailable(!localDate1.isAfter(localDate2));
                }
                courseInfoDtoList.add(courseInfoDto);
            });
            result.setData(courseInfoDtoList);
        }
        return result;
    }

    @Override
    public ResponseMessage getCourseDetail(String id) {
        ResponseMessage result;
        CourseInfo courseInfo = courseInfoMapper.selectCourseInfoById(id);
        if (courseInfo != null) {
            CourseInfoDto courseInfoDto = CourseInfoConvertor.convertToDto(courseInfo);
            AttachmentsDto attachmentsDetail = attachmentsService.getAttachmentsDtoById(courseInfo.getAttachment());
            AttachmentsDto frontCover = attachmentsService.getAttachmentsDtoById(courseInfo.getFrontCover());
            courseInfoDto.setAttachmentDetail(attachmentsDetail);
            courseInfoDto.setFrontCoverDetail(frontCover);
            Date currentTime = new Date();
            if (courseInfoDto.getEndTime() != null) {
                LocalDate localDate1 = currentTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                LocalDate localDate2 = courseInfoDto.getEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                courseInfoDto.setAvailable(!localDate1.isAfter(localDate2));
            }
            result = ResponseMessageUtility.createSuccess();
            result.setData(courseInfoDto);
        } else {
            result = ResponseMessageUtility.createError("获取课程详情失败。");
        }
        return result;
    }

    @Override
    public ResponseMessage getStudyGardenList(PageDomain pageDomain) {
        ResponseMessage result = ResponseMessageUtility.createSuccess();
        int offset = (pageDomain.getPageNum() - 1) * pageDomain.getPageSize();
        int size = pageDomain.getPageSize();
        List<CourseInfo> courseInfoList = courseInfoMapper.selectStudyGardenListByPage(offset, size);
        if (courseInfoList != null && !courseInfoList.isEmpty()) {
            List<CourseInfoDto> courseInfoDtoList = new ArrayList<>();
            courseInfoList.forEach(courseInfo -> {
                String frontCover = courseInfo.getFrontCover();
                CourseInfoDto courseInfoDto = CourseInfoConvertor.convertToDto(courseInfo);
                courseInfoDto.setFrontCoverDetail(attachmentsService.getAttachmentsDtoById(frontCover));
                Date currentTime = new Date();
                if (courseInfoDto.getEndTime() != null) {
                    LocalDate localDate1 = currentTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    LocalDate localDate2 = courseInfoDto.getEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    courseInfoDto.setAvailable(!localDate1.isAfter(localDate2));
                }
                courseInfoDtoList.add(courseInfoDto);
            });
            result.setData(courseInfoDtoList);
        }
        return result;
    }

    @Override
    public ResponseMessage getStudyGardenItemDetail(String id) {
        return getCourseDetail(id);
    }
}




